import { observable, action } from 'mobx'
import {axiosFetch, handleResp} from "../../util/common/http";
import {Toast} from "antd-mobile";
import cache from "../../util/common/cache";
import {testTel} from "../../util/common/kit";
import history from "../../util/router/history";

export class UserInfoStore {
	@observable userInfo: {
		userId: string,
		userPhoto: string|null,
		userNickName: string,
		userPhone: string,
	}|null = null;

	// 用户状态(1:可编辑 0:用户不存在or出错了)
	@observable userStatus: number = 1;
	// 提交按钮状态(1:禁用 2:可用 3:操作中)
	@observable submitBtnStatus: number = 2;

	/**
	 * 获取登录人基本信息
	 */
	@action initUserInfo = async () => {
		const fetchResp = await axiosFetch("/user/login/query", {
			method: 'GET'
		});
		if (handleResp(fetchResp)) {
			this.userInfo = fetchResp.context;
		} else {
			this.userStatus = 0;
		}
	};

	/**
	 * 更新用户头像
	 * @param value
	 */
	@action updateUserPhoto = async (value: string|null) => {
		if (this.userInfo) {
			// 若是null,则删除服务器上的物理存储的图片
			if (value == null) {
				const delResp = await axiosFetch("/user/photo/delete", {
					method: 'DELETE',
					data: {
						userPhoto: this.userInfo.userPhoto
					}
				});

				if (handleResp(delResp)) {
					this.userInfo.userPhoto = null;
				}
			} else {
				this.userInfo.userPhoto = value;
			}
		}
	};

	/**
	 * 更新用户昵称
	 * @param value
	 */
	@action updateUserNickName = (value: string) => {
		if (this.userInfo) {
			this.userInfo.userNickName = value;
		}
	};

	/**
	 * 更新用户手机号
	 * @param value
	 */
	@action updateUserPhone = (value: string) => {
		if (this.userInfo) {
			this.userInfo.userPhone = value;
		}
	};

	/**
	 * 修改用户基本信息
	 */
	@action updateUserInfo = async () => {
		if (!this.userInfo) {
			return;
		}
		if (!this.userInfo.userNickName) {
			Toast.fail("用户昵称必填!", 1.5);
			return false;
		}
		if (!this.userInfo.userPhone) {
			Toast.fail("用户手机必填!", 1.5);
			return false;
		}
		if (!testTel(this.userInfo.userPhone)) {
			return false;
		}

		this.submitBtnStatus = 3;
		const fetchResp = await axiosFetch("/user/update", {
			method: 'PUT',
			data: this.userInfo
		});

		this.submitBtnStatus = 2;
		if (handleResp(fetchResp)) {
			// 修改成功后,同时修改浏览器本地存储中的登录信息
			const loginDataStr = localStorage.getItem(cache.LOGIN_DATA);
			if (loginDataStr) {
				const loginData = JSON.parse(loginDataStr);
				loginData.loginVO = {
					userNickName: this.userInfo.userNickName,
					userPhone: this.userInfo.userPhone
				};
				localStorage.setItem(cache.LOGIN_DATA, JSON.stringify(loginData));
			}
			history.goBack();
		}
	};

}

export default new UserInfoStore();
